package com.zerosky.crm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zerosky.crm.po.Branch;
import com.zerosky.crm.po.Department;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.Objective;
import com.zerosky.crm.po.Pluralize;
import com.zerosky.crm.service.BranchService;
import com.zerosky.crm.service.DepartmentService;
import com.zerosky.crm.service.ObjectiveService;
import com.zerosky.crm.service.PluralizeService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.PageInfo;

/**
 * 统计图表Controller
 * 
 * @author 钟璟
 *
 */
@Controller
public class ObjectiveController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(ObjectiveController.class); // 日志

	@Resource(name = "objectiveService")
	private ObjectiveService objectiveService;

	@Resource(name = "branchService")
	private BranchService branchService;

	@Resource(name = "pluralizeService")
	private PluralizeService pluralizeService;

	@Resource(name = "departmentService")
	private DepartmentService departmentService;

	/**
	 * 获取销售目标数据
	 * 
	 * @param deptId部门
	 * @param page分页
	 * @param limit总页数
	 * @param name搜索名称
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("getSalesTarget.do")
	@ResponseBody
	public Map<String, Object> getSalesTarget(String deptId, String branchId, String teamId, Integer page,
			Integer limit, String name, HttpServletRequest request, HttpSession session) {// 检查是否设置目标
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		PageInfo<Objective> pageInfo = new PageInfo<Objective>();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pageNo", page);
			map.put("pageSize", limit);
			map.put("name", name);
			if (user.getQuarters().equals("1")) {// 团队长
				map.put("teamId", teamId);
				pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
			} else if (user.getQuarters().equals("2")) {// 部门经理
				map.put("teamId", teamId);
				map.put("branchId", branchId);
				if (teamId != null && teamId != "") {
					pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
				} else {
					pageInfo = objectiveService.getObjectiveStatisticsByTeam(map);
				}
			} else if (user.getQuarters().equals("3")) {// 公司负责人
				if (deptId == null || deptId == "") {
					deptId = user.getDept().getDeptId();
				}
				if (teamId != null && teamId != "") {
					map.put("teamId", teamId);
					pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
				} else if (branchId != null && branchId != "") {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					pageInfo = objectiveService.getObjectiveStatisticsByTeam(map);
				} else {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					map.put("deptId", deptId);
					pageInfo = objectiveService.getObjectiveStatisticsByBranch(map);
				}
			} else if (user.getQuarters().equals("7")) {// 分部运营
				if (teamId != null && teamId != "") {
					map.put("teamId", teamId);
					pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
				} else if (branchId != null && branchId != "") {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					pageInfo = objectiveService.getObjectiveStatisticsByTeam(map);
				} else {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					map.put("deptId", deptId);
					pageInfo = objectiveService.getObjectiveStatisticsByBranch(map);
				}
			} else if (user.getQuarters().equals("5") || user.getQuarters().equals("6")) {// 总部负责人或总部管理员
				if (teamId != null && teamId != "") {
					map.put("teamId", teamId);
					pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
				} else if (branchId != null && branchId != "") {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					pageInfo = objectiveService.getObjectiveStatisticsByTeam(map);
				} else if (deptId != null && deptId != "") {
					map.put("teamId", teamId);
					map.put("branchId", branchId);
					map.put("deptId", deptId);
					pageInfo = objectiveService.getObjectiveStatisticsByBranch(map);
				} else {
					pageInfo = objectiveService.getObjectiveStatisticsByDept(map);
				}
			} else {
				map.put("employeeId", user.getEmployeeId());
				pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
				pageInfo.getList().get(0).setCreatePeople("emptys");
			}
			json.put("data", pageInfo.getList());
			json.put("total", pageInfo.getPageCount());
			json.put("code", 0);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	@RequestMapping("getUserTarget.do")
	@ResponseBody
	public Map<String, Object> getUserTarget(HttpServletRequest request, HttpSession session) {// 检查是否设置目标
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		PageInfo<Objective> pageInfo = new PageInfo<Objective>();
		List<Objective> listObj = new ArrayList<Objective>(); // 接受兼任部门目标对象
		Map<String, Object> pramAll = new HashMap<String, Object>();// 查询全部部门的条件
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pageNo", 1);
			map.put("pageSize", 10);
			pageInfo = objectiveService.getObjectiveStatisticsByPersonal(map);
			Objective objective = pageInfo.getList().get(0);
			if (user.getQuarters().equals("1")) {// 团队长,获取我的团队信息
				Map<String, Object> prams = new HashMap<String, Object>();// 查询全部部门的条件
				List<Branch> list = new ArrayList<Branch>();
				pramAll.put("queryByCompany", "1");
				prams.put("employeeId", user.getEmployeeId());
				prams.put("pluralizeType", "1");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(prams);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);
				list.add(user.getTeam());// 添加自己所在团队
				for (Pluralize pluralize : pluralizeList) {
					for (Branch dept : listAll) {
						if (!pluralize.getDeptId().equals(user.getTeam().getBranchId())) {
							if (pluralize.getDeptId().equals(dept.getBranchId())) {
								list.add(dept);// 添加兼任团队
							}
						}
					}
				}
				for (Branch team : list) {
					map.put("teamId", team.getBranchId());
					Objective myTeam = objectiveService.getTeam(map);// 获取兼任团队的销售目标
					listObj.add(myTeam);
				}
				json.put("team", listObj);
			} else if (user.getQuarters().equals("2")) {// 部门经理，获取我的部门和兼任部门信息
				List<Branch> list = new ArrayList<Branch>();
				pramAll.put("isBranch", "isBranch");
				map.put("employeeId", user.getEmployeeId());
				map.put("pluralizeType", "2");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				List<Branch> listAll = branchService.getBranchAllList(pramAll);

				list.add(user.getBranch());
				for (Pluralize pluralize : pluralizeList) {
					for (Branch dept : listAll) {
						if (!pluralize.getDeptId().equals(user.getBranch().getBranchId())) {
							if (pluralize.getDeptId().equals(dept.getBranchId())) {
								list.add(dept);
							}
						}
					}
				}
				for (Branch team : list) {
					map.put("branchId", team.getBranchId());
					Objective myTeam = objectiveService.getBranch(map);// 获取兼任部门的销售目标
					listObj.add(myTeam);
				}
				json.put("team", listObj);
			} else if (!user.getQuarters().equals("0")) {// 公司负责人，获取我的公司信息

				List<Department> list = new ArrayList<Department>();
				map.put("canNotReadAllMessage", false);
				List<Department> listDept = departmentService.getDepartmentList(map);
				map.put("employeeId", user.getEmployeeId());
				map.put("pluralizeType", "3");
				List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
				if (!user.getQuarters().equals("7") && !user.getQuarters().equals("8")) {
					list.add(user.getDept());
				}
				for (Pluralize pluralize : pluralizeList) {
					for (Department dept : listDept) {
						if (!pluralize.getDeptId().equals(user.getDept().getDeptId())) {
							if (pluralize.getDeptId().equals(dept.getDeptId())) {
								list.add(dept);
							}
						}
					}
				}
				for (Department dept : list) {
					map.put("deptId", dept.getDeptId());
					Objective myTeam = objectiveService.getDept(map);// 获取兼任分公司的销售目标
					listObj.add(myTeam);
				}
				json.put("team", listObj);
			}
			json.put("data", objective);
			json.put("code", 0);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	@RequestMapping("addObjective.do")
	@ResponseBody
	public Map<String, Object> addObjective(Double money, String id, String teamId, String deptId, String branchId,
			HttpServletRequest request, HttpSession session) {// 检查是否设置目标
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		Objective objective = new Objective();
		try {
			String srtId = UUID.randomUUID().toString();
			objective.setCreateDate(new Date());
			objective.setCreatePeople(user.getName());
			objective.setObjectiveId(srtId);
			objective.setObjectiveMoney(money);
			objective.setStartDate(testForDate());
			objective.setEndDate(testForDatelast());
			if (deptId != null && !"".equals(deptId) && branchId != null && !"".equals(branchId) && teamId != null
					&& !"".equals(teamId)) {// 设置个人目标
				objective.setEmployeeId(id);
			} else if (deptId != null && !"".equals(deptId) && branchId != null && !"".equals(branchId)) {// 设置团队目标
				objective.setTeamId(id);
			} else if (deptId != null && !"".equals(deptId)) {// 设置部门目标
				objective.setBranchId(id);
			} else if (deptId == null || deptId == "") {// 设置分公司目标
				objective.setDeptId(id);
			} else {
				json.put("code", -1);
				return json;
			}
			/*
			 * if (user.getQuarters().equals("1")) {// 团队长
			 * objective.setEmployeeId(id); } else if
			 * (user.getQuarters().equals("2")) {// 部门经理
			 * objective.setTeamId(id); } else if
			 * (user.getQuarters().equals("3")) {// 公司负责人
			 * objective.setBranchId(id); } else if
			 * (user.getQuarters().equals("7")) {// 分部运营
			 * objective.setBranchId(id); } else if
			 * (user.getQuarters().equals("5") ||
			 * user.getQuarters().equals("6")) {// 总部负责人或总部管理员
			 * 
			 * }
			 */
			objectiveService.addInvite(objective);
			json.put("code", 0);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	public Date testForDate() throws ParseException {
		// 规定返回日期格式
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date theDate = calendar.getTime();
		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		gcLast.setTime(theDate);
		// 设置为第一天
		gcLast.set(Calendar.DAY_OF_MONTH, 1);
		String day_first = sf.format(gcLast.getTime());
		// 打印本月第一天
		return sf.parse(day_first);
	}

	// 2、获取当月最后一天
	public Date testForDatelast() throws ParseException {
		// 获取Calendar
		Calendar calendar = Calendar.getInstance();
		// 设置日期为本月最大日期
		calendar.set(Calendar.DATE, calendar.getActualMaximum(calendar.DATE));
		// 设置日期格式
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String ss = sf.format(calendar.getTime());
		return sf.parse(ss);
	}
}
